package thread;

public class Demo18 {
    public static void main(String[] args) throws InterruptedException {
        //三个线程循环打印ABC十次
        Object locker1 = new Object();
        Object locker2 = new Object();
        Object locker3 = new Object();
        Thread t1 = new Thread(()->{
           try{
               for (int i = 0; i < 10; i++) {
                   //等待t2打印
                   synchronized (locker1){
                       locker1.wait();
                   }
                   System.out.print("A");
                   //唤醒t2
                   synchronized (locker2){
                       locker2.notify();
                   }
               }
           }catch (InterruptedException e){
               throw new RuntimeException();
           }
        });
        Thread t2 = new Thread(()->{
            try{
                for (int i = 0; i < 10; i++) {
                    //等待t3打印
                    synchronized (locker2){
                        locker2.wait();
                    }
                    System.out.print("B");
                    //唤醒t3
                    synchronized (locker3){
                        locker3.notify();
                    }
                }
            }catch (InterruptedException e){
                throw new RuntimeException();
            }
        });
        Thread t3 = new Thread(()->{
            try{
                for (int i = 0; i < 10; i++) {
                    //等待t1打印
                    synchronized (locker3){
                        locker3.wait();
                    }
                    System.out.print("C");
                    //唤醒t1
                    synchronized (locker1){
                        locker1.notify();
                    }
                }
            }catch (InterruptedException e){
                throw new RuntimeException();
            }
        });

        t1.start();
        t2.start();
        t3.start();

        //等待一会，确保上述三个线程都在等待
        Thread.sleep(1000);
        //主线程通知t1进行打印，使上述循环开始
        synchronized (locker1){
            locker1.notify();
        }

        t1.join();
        t2.join();
        t3.join();
    }
}
